import { computed } from "vue";
import type { MenuOption } from "naive-ui";
import { useStorage } from "@vueuse/core";

export function useMenuCache() {
  // 缓存菜单数据
  const menuCache = useStorage<{
    options: MenuOption[];
    timestamp: number;
  }>("menu-cache", {
    options: [],
    timestamp: 0,
  });

  // 缓存过期时间（30分钟）
  const CACHE_EXPIRE_TIME = 30 * 60 * 1000;

  // 检查缓存是否有效
  const isCacheValid = computed(() => {
    const now = Date.now();
    return (
      menuCache.value.options.length > 0 &&
      now - menuCache.value.timestamp < CACHE_EXPIRE_TIME
    );
  });

  // 更新缓存
  const updateCache = (options: MenuOption[]) => {
    menuCache.value = {
      options,
      timestamp: Date.now(),
    };
  };

  // 获取缓存的菜单
  const getCachedMenu = () => {
    return isCacheValid.value ? menuCache.value.options : null;
  };

  return {
    updateCache,
    getCachedMenu,
    isCacheValid,
  };
}
